using System;
using System.Reflection;

namespace SharePoint.DataMapper
{
	public static class AttributeService
	{
		public static TAttribute GetAttribute<TAttribute, TMember>()
			where TAttribute : Attribute
		{
			return GetAttribute<TAttribute>(typeof (TMember));
		}

		public static T GetAttribute<T>(this MemberInfo member)
			where T : Attribute
		{
			T[] attributes = member.GetCustomAttributes(typeof(T), false) as T[];
			if (attributes != null && attributes.Length != 0 && attributes[0] != null)
			{
				return attributes[0];
			}
			return default(T);
		}


		public static TAttribute GetInterfaceAttribute<TAttribute, TMember>()
			where TAttribute : Attribute
		{
			return GetInterfaceAttribute<TAttribute>(typeof(TMember));
		}

		public static T GetInterfaceAttribute<T>(this MemberInfo member)
			where T : Attribute
		{
			T[] attributes = member.GetCustomAttributes(typeof(T), false) as T[];
			if (attributes != null && attributes.Length != 0 && attributes[0] != null)
			{
				return attributes[0];
			}
			Type[] interfaces = member.DeclaringType.GetInterfaces();
			foreach (Type i in interfaces)
			{
				MemberInfo[] iMembers = i.GetMember(member.Name, member.MemberType, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
				foreach (MemberInfo iMember in iMembers)
				{
					T attribute = GetAttribute<T>(iMember);
					if (attribute != null)
					{
						return attribute;
					}
				}
			}
			return default(T);
		}


		public static TAttribute[] GetAttributes<TAttribute, TMember>()
			where TAttribute : Attribute
		{
			return GetAttributes<TAttribute>(typeof(TMember));
		}

		public static T[] GetAttributes<T>(this MemberInfo member)
			where T : Attribute
		{
			return member.GetCustomAttributes(typeof(T), false) as T[];
		}
	}
}